package org.egrit.geometry;

import com.vividsolutions.jts.geom.Coordinate;
import com.vividsolutions.jts.geom.CoordinateSequence;
import com.vividsolutions.jts.geom.Envelope;

/**
 * A {@linkplain CoordinateSequence} for a single point.
 * 
 * @author michael
 */
public class PointCoordinateSequence implements CoordinateSequence {

    Coordinate coord = new Coordinate();
    
    @Override
    public int getDimension() {
        return 2;
    }
    
    private void checkIndex(int index) {
        if (index != 0) {
            throw new IndexOutOfBoundsException("0 is the only valid index");
        }
    }

    @Override
    public Coordinate getCoordinate(int i) {
        checkIndex(i);
        return new Coordinate(coord);
    }

    @Override
    public Coordinate getCoordinateCopy(int i) {
        return getCoordinate(i);
    }

    @Override
    public void getCoordinate(int index, Coordinate coord) {
        checkIndex(index);
        if (coord == null) {
            throw new IllegalArgumentException("coord must not be null");
        }
        coord.setCoordinate(coord);
    }

    @Override
    public double getX(int index) {
        checkIndex(index);
        return coord.x;
    }

    @Override
    public double getY(int index) {
        checkIndex(index);
        return coord.y;
    }

    @Override
    public double getOrdinate(int index, int ordinateIndex) {
        checkIndex(index);
        switch (ordinateIndex) {
            case 0: return coord.x;
            case 1: return coord.y;
            default:
                throw new IllegalArgumentException("ordinateIndex must be 0 or 1");
        }
    }

    @Override
    public int size() {
        return 1;
    }

    @Override
    public void setOrdinate(int index, int ordinateIndex, double value) {
        checkIndex(index);
        switch (ordinateIndex) {
            case 0: 
                coord.x = value;
                break;
                
            case 1: 
                coord.y = value;
                break;
                
            default:
                throw new IllegalArgumentException("ordinateIndex must be 0 or 1");
        }
    }
    
    public void setXY(double x, double y) {
        coord.x = x;
        coord.y = y;
    }

    @Override
    public Coordinate[] toCoordinateArray() {
        return new Coordinate[] { getCoordinate(0) };
    }

    @Override
    public Envelope expandEnvelope(Envelope env) {
        Envelope expanded = new Envelope(env);
        expanded.expandToInclude(coord);
        return expanded;
    }

    @Override
    public Object clone() {
        PointCoordinateSequence copy = new PointCoordinateSequence();
        copy.coord.setCoordinate(coord);
        return copy;
    }
    
}
